package com.lagou.hbasework;

import org.apache.hadoop.hbase.Cell;
import org.apache.hadoop.hbase.CellUtil;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.Delete;
import org.apache.hadoop.hbase.client.Durability;
import org.apache.hadoop.hbase.client.Get;
import org.apache.hadoop.hbase.client.HTableInterface;
import org.apache.hadoop.hbase.coprocessor.BaseRegionObserver;
import org.apache.hadoop.hbase.coprocessor.ObserverContext;
import org.apache.hadoop.hbase.coprocessor.RegionCoprocessorEnvironment;
import org.apache.hadoop.hbase.regionserver.wal.WALEdit;
import org.apache.hadoop.hbase.util.Bytes;

import java.io.IOException;
import java.util.*;

public class MyProcessor extends BaseRegionObserver {
    @Override
    public void postDelete(ObserverContext<RegionCoprocessorEnvironment> e, Delete delete, WALEdit edit, Durability durability) throws IOException {
        HTableInterface friendManner = e.getEnvironment().getTable(TableName.valueOf("friendManner"));
        //获取到rowKey
        byte[] rowKeyUId = delete.getRow();
        //获取到cell对象
        NavigableMap<byte[], List<Cell>> familyCellMap = delete.getFamilyCellMap();
        Set<Map.Entry<byte[], List<Cell>>> entries = familyCellMap.entrySet();
        for (Map.Entry<byte[], List<Cell>> entry : entries) {
            //列族信息
            byte[] key = entry.getKey();
            System.out.println(Bytes.toString(key));
            //列族中的列信息
            List<Cell> cells = entry.getValue();

            for (Cell cell : cells) {
                //rowKey信息
                byte[] rowKey = CellUtil.cloneRow(cell);
                //列
                byte[] col = CellUtil.cloneQualifier(cell);
                //删除前进行数据有效性校验
                boolean b = friendManner.exists(new Get(col).addColumn(Bytes.toBytes("friends"), rowKey));
                if (b) {
                    //执行删除
                    Delete delete1 = new Delete(col).addColumn(Bytes.toBytes("friends"), rowKey);
                    friendManner.delete(delete1);
                }
            }
        }

    }
}
